import { getRandomId } from "./utils";

export interface ModuleConfig {
    [key: string]: unknown;
}

/**
 * 基础模块
 * @param C 模块配置
 */
export abstract class BaseModule<C extends ModuleConfig = ModuleConfig> {
    protected _id: string = getRandomId();
    /** 唯一标识 */
    get id() {
        return this._id;
    }
    protected _inited: boolean = false;
    /** 是否初始化 */
    get inited() {
        return this._inited;
    }
    /** 配置 */
    config?: C;

    /**
     * 初始化模块
     * @returns 模块实例
     */
    async init(config?: C): Promise<this> {
        if (this._inited) {
            throw new Error("Module has been initialized");
        }
        if (!config && !this.config) {
            throw new Error("Config is required");
        }
        this._inited = true;
        this.config = config;
        await this._init(config ?? this.config!);
        return this;
    }
    /** 模块初始化方法 */
    protected abstract _init(config: C): Promise<void>;
    /**
     * 销毁模块
     * @returns 模块 id
     */
    async destroy(): Promise<string> {
        this._inited = false;
        await this._destroy();
        return this.id;
    }
    /** 模块销毁方法 */
    protected abstract _destroy(): Promise<void>;
}
